using System;

namespace UDS.Management.Data.Deployment
{
    internal static class PreRequisiteCheck
    {
        /// <summary>
        /// To avoid collation conflicts, we have to unify the collation of all the database we created.
        /// All the database must use SQL_Latin1_General_CP1_CI_AS collation.
        /// </summary>
        public const string RequiredCollation = "SQL_Latin1_General_CP1_CI_AS";
        private static string message = "Version {0} is not supported.  Please install {1} from {2} on {3} to be able to continue.";
        private static Version requiredSqlVersion = new Version("10.00.2531.00");  // SQL 2008 SP1
        private static string requiredSqlVersionString = "SQL Server SP1 (build 2531) for SQL Server 2008";
        private static string downloadLocation = "http://www.microsoft.com/downloads/details.aspx?FamilyID=66ab3dbb-bf3e-4f46-9559-ccc6a4f9dc19&displaylang=en";

        public static bool CheckSQLServerVersion(Database db)
        {
            if (db.InstalledSqlVersion >= requiredSqlVersion)
            {
                return true;
            }
            else
            {
                throw new VersionException(String.Format(message, db.InstalledSqlVersionString, requiredSqlVersionString, downloadLocation, db.ServerName));
            }
        }

        /// <summary>
        /// Ensures the linked server is set correctly for the source and linked servers.
        /// </summary>
        /// <param name="sourceServerName">The server to connect to in order to check the linked server</param>
        /// <param name="linkedServerName">The name of the linked server to check</param>
        /// <exception cref="ValidationException">A validation exception is thrown if the linked server isn't setup correctly</exception>
        public static void CheckLinkedServer(string sourceServerName, String linkedServerName)
        {
            if (sourceServerName == null) throw new ArgumentNullException("sourceServerName", "An invalid source server was specified");
            if (sourceServerName == String.Empty) throw new ArgumentException("An empty source server was specified", "sourceServerName");
            if (linkedServerName == null) throw new ArgumentNullException("linkedServerName", "An invalid link server was specified");
            if (linkedServerName == String.Empty) throw new ArgumentException("An empty link server was specified", "sourceServerName");

            Database SourceDB = new Database(sourceServerName);
            Database LinkDB = new Database(linkedServerName);
            string LinkedServerNetBiosName = LinkDB.GetNetBiosServerName();

            try
            {
                if (!SourceDB.PingLinkedServer(LinkedServerNetBiosName))
                {
                    throw new ValidationException("Could not test linked server connection");
                }
            }
            catch (Exception ex)
            {
                throw new ValidationException(string.Format("Wrong setting on the Linked server definition at the branch [{0}] for ServiceGroup DB server [{1}]. Please refer to the IPTV/SQL documentation to fix the linked server. Exception: [{2}] occurred.", SourceDB.GetNetBiosServerName(), LinkedServerNetBiosName, ex.Message));
            }
        }

        public static void CheckServerCollation(string sourceServerName)
        {
            Database db = new Database(sourceServerName);
            string collation = db.GetServerCollation();

            //if (collation.ToLower().Contains("_ci_") || collation.ToLower().EndsWith("_ci"))
            //    return;
            //throw new ValidationException(String.Format("Collation setting {0} is not case insensitive for the sql server {1}. Reinstall sql server with case insensitive collation.",
            //    collation, db.GetNetBiosServerName()));
            if (collation != RequiredCollation)
            {
                throw new ValidationException(
                    String.Format("Collation setting {0} for the sql server {1} is not supported. Reinstall sql server with " + RequiredCollation + "collation.",
                    collation,
                    db.GetNetBiosServerName()));
            }
        }

        public static void CheckCollationMatch(Database db)
        {
            string dbCollation = db.GetDatabaseCollation();
            string serverCollation = db.GetServerCollation();

            if (dbCollation != serverCollation)
                throw new ValidationException(String.Format("Database collation {0} for database {1} does not match with server collation {2} of sql server {3}. If data is not important, " +
                    "then delete the database and inherit server collation while creating manually, or create the database using this tool.",
                    dbCollation, db.DatabaseName, serverCollation, db.GetNetBiosServerName()));
        }
    }

}
